package com.yshkj.payment.utils;

import org.apache.commons.lang.StringUtils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * sha1加密算法辅助类
 * Created by 唐旭 on 2015/12/4.
 */
public abstract class SHA1Utils {

    private SHA1Utils() {
    }

    public static String encode(Map<String, Object> map, String separator) {
        List<String> list = new ArrayList<>(map.keySet());
        Collections.sort(list);
        StringBuilder builder = new StringBuilder();
        for (String item : list) {
            String format = String.format("%s=%s", item, map.get(item) + separator);
            builder.append(format);
        }
        if (StringUtils.isNotEmpty(separator)) {
            builder.deleteCharAt(builder.length() - 1);
        }

        return sha1(builder.toString());
    }

    public static String encode(Map<String, Object> map) {
        return encode(map, "&");
    }

    public static String sha1(String string) {
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-1");
            digest.update(string.getBytes());
            byte messageDigest[] = digest.digest();
            StringBuilder hexString = new StringBuilder();
            for (byte aMessageDigest : messageDigest) {
                String shaHex = Integer.toHexString(aMessageDigest & 0xFF);
                if (shaHex.length() < 2) {
                    hexString.append(0);
                }
                hexString.append(shaHex);
            }
            return hexString.toString();
        } catch (NoSuchAlgorithmException e) {
            throw new IllegalArgumentException(e);
        }
    }
}
